package com.eeGroup.config;

import com.eeGroup.service.LoginService;
import com.eeGroup.vo.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserRealm extends AuthenticatingRealm {

    @Autowired
    private LoginService loginService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        String password = new String(upToken.getPassword());

        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            throw new AuthenticationException("账号密码不能为空！");
        }


        User user = loginService.login2(username, password);

        if (user!=null) {
            return new SimpleAuthenticationInfo(user, password, getName());
        } else {
            throw new AuthenticationException("账号或密码错误！");
        }
    }
}
